/*
 * StringInput.cpp
 *
 *  Created on: 18/11/2013
 *      Author: fernando
 */

#include "StringInput.h"
#include <string>
#include "SDL.h"

using std::string;


const SDL_Color textColor = {0, 0, 0};
const char FONT[] = "Fonts/FatMarker.ttf";
const unsigned int TAMMAXIMO = 10;

StringInput::StringInput(){
    str = "";
    font = TTF_OpenFont(FONT, 24);
    text = NULL;
}

StringInput::~StringInput(){
    SDL_FreeSurface(text);
    TTF_CloseFont(font);
}

void StringInput::handle_input(SDL_Event& event){
        std::string temp = str;
        if (str.length() <= TAMMAXIMO){
        	//Si es un espacio
            if (event.key.keysym.unicode == (Uint16)' '){
                str += (char)event.key.keysym.unicode;
            //Si es un numero
            }else if ((event.key.keysym.unicode >= (Uint16)'0')
            		&& (event.key.keysym.unicode <= (Uint16)'9')){
                str += (char)event.key.keysym.unicode;
            //Si es mayuscula, la paso a minuscula
            }else if ((event.key.keysym.unicode >= (Uint16)'A')
            		&& (event.key.keysym.unicode <= (Uint16)'Z')){
                 str += tolower((char)event.key.keysym.unicode);
            //Si es minuscula
            }else if ((event.key.keysym.unicode >= (Uint16)'a')
            		&& (event.key.keysym.unicode <= (Uint16)'z')){
                str += (char)event.key.keysym.unicode;
            }
        }
        //Si apreta borrar
        if ((event.key.keysym.sym == SDLK_BACKSPACE) && (str.length() != 0)){
            str.erase(str.length() - 1);
        }
        if (str != temp){
            SDL_FreeSurface(text);
            text = TTF_RenderText_Solid(font, str.c_str(), textColor);
        }
}

void StringInput::show(unsigned int x, unsigned int y, SDL_Surface* screen){
		if (text != NULL){
			SDL::apply_surface(x, y, text, screen, NULL);
		}
}

void StringInput::showHidden(unsigned int x, unsigned int y,
		SDL_Surface* screen){
		string tmp = "";
		if (text != NULL){
			for (unsigned int i = 0; i < str.size(); i++){
				tmp += '*';
			}
			SDL_FreeSurface(text);
			text = TTF_RenderText_Solid(font, tmp.c_str(), textColor);
			SDL::apply_surface(x, y, text, screen, NULL);
		}
}

string StringInput::getStringValue(){
	return str;
}

void StringInput::emptyValue(){
	str = "";
    text = NULL;
}

